package com.higgins.lawapp.server;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import com.higgins.lawapp.client.settings.dataItemModel.DataItemDTO;
import com.higgins.lawapp.client.settings.dataModel.DataSourceLevelDTO;
import com.higgins.lawapp.client.settings.rpc.InternetService;
import com.higgins.lawapp.server.dataItemModel.DataItem;
import com.higgins.lawapp.server.dataModel.DataSourceLevel;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.QueueFactory;
import com.google.appengine.api.taskqueue.TaskOptions.Builder;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;


/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class InternetServiceImpl extends RemoteServiceServlet implements InternetService {
	DatastoreService myDatastoreService = DatastoreServiceFactory.getDatastoreService();

	@Override
	public List<DataItemDTO> executeScreenScraping(
			DataSourceLevelDTO dataSourceLevelDTO, String urlFileName,
			Boolean concat) throws IllegalArgumentException {
		
		List<DataItemDTO> dataItemDTOs = new ArrayList<DataItemDTO>();;
		String status = "Successfully Screen Scraped!!!";
		try	{
			InternetManager internetManager = new InternetManager();
			
			DataSourceLevel dataSourceLevel = new DataSourceLevel(dataSourceLevelDTO);
			
			
			// Set urlFilename
			List<DataItem> dataItems = null;
			dataItems = internetManager.executeDataItemCollection(dataSourceLevel, urlFileName, concat);	
			
			if (dataItems!=null)	{
				Iterator<DataItem> iterator = dataItems.iterator();
				while (iterator.hasNext())	{
					DataItem dataItem = iterator.next();
					DataItemDTO dataItemDTO = dataItem.getDataItemDTO();
					dataItemDTOs.add(dataItemDTO);
				}
			}
		}	catch (Exception e)	{
			status="Unsuccessfully deleted: " + e.toString();
		}
		return dataItemDTOs;
	}

	@Override
	public String startFullDataCollection() throws IllegalArgumentException {
		System.out.println("InternetServiceImpl.startFullDataCollection()");
		String status = "Success";
		try	{
			Queue queue = QueueFactory.getQueue("data-collection-queue");
			queue.add(Builder.withUrl("/dataCollection"));
		} catch (Exception e)	{
			status = "ERROR: "+e.toString();
		}		
		System.out.println("InternetServiceImpl.startFullDataCollection()... Complete");
		return status;
	}
}
